/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-04-23 15:40:10
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-04-23 15:54:25
 */
import { useRef, useEffect } from "react";
function useEventListener(eventName, handler, element = window) {
  const savedHandler = useRef(null);
  useEffect(() => {
    savedHandler.current = handler;
  }, [handler]);
  useEffect(() => {
    const isSupported = element && element.addEventListener;
    if (!isSupported) return;
    const eventListener = (event) => savedHandler.current(event);
    element.addEventListener(eventName, eventListener);
    return () => {
      element.removeEventListener(eventName, eventListener);
    };
  }, [eventName, element]);
}

export default useEventListener;
